<template>
    <div class="title">
        修改商品
    </div>
    <el-form
        :model="formData"
        :rules="rules"
        label-width="auto"
        style="max-width: 1000px"
        ref="formRef"
        :hide-required-asterisk="true"
    >
        <el-form-item label="商品名称" prop="name">
            <el-input v-model="formData.name" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="商品分类" prop="category" style="width: 250px">
            <el-select
                placeholder="请选择商品分类"
                v-model="formData.category"
            >
                <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                ></el-option>
            </el-select>
        </el-form-item>
        <el-form-item label="商品价格" prop="price">
    <el-input-number 
      v-model="formData.price"
      :min="0.01"
      :precision="2"
      :step="0.5"
      controls-position="right"
    />
  </el-form-item>
        <el-form-item label="商品图片" prop="img">
            <el-upload
                class="avatar-uploader"
                action="http://8.137.157.16:9002/goods/goods_img_upload"
                :show-file-list="false"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
            >
                <img v-if="formData.img" :src="formData.img" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
        </el-form-item>
        <el-form-item label="商品描述" prop="desc">
            <el-input v-model="formData.desc" type="textarea" style="width: 100%;" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="submitForm">保存修改</el-button>
        </el-form-item>
    </el-form>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { editGoods } from '../../api/account'
import { serveUrl } from '../../utils/common'

const route = useRoute()
const router = useRouter()

// 表单数据结构

const formData = ref({
  id: '',
  name: '',
  category: '',
  price: 0, // 直接绑定数值
  desc: '',
  img: ''
});

const submitData = {
  ...formData.value,
  price: formData.value.price.toFixed(2), // 转为字符串并保留两位小数
  imgUrl: formData.value.img.replace(serveUrl, ''),
  goodsDesc: formData.value.desc
};
const submitForm = async () => {
  try {
    const submitData = {
      ...formData.value,
      price: formData.value.price.toFixed(2), // 转为字符串并保留两位小数
      imgUrl: formData.value.img.replace(serveUrl, ''),
      goodsDesc: formData.value.desc
    };
    console.log('提交的图片地址:', submitData.imgUrl); // 添加日志输出
    const res = await editGoods(submitData);
    console.log(res);
    

    if (res.code === 0) {
      ElMessage.success('修改成功');
      setTimeout(() => {
        router.push('/goodsList');
      }, 1500);
    } else {
      ElMessage.error(res.msg || '修改失败');
    }
  } catch (error) {
    ElMessage.error('网络请求失败');
  }
};


// 解析路由参数
const parseRouteData = () => {
  try {
    // 安全解码数据
    const rawData = decodeURIComponent(route.query.data || '')
    const goodsData = JSON.parse(rawData)
    
    if (!goodsData.id) throw new Error('无效的商品数据')
    
    formData.value = {
      id: goodsData.id,
      name: goodsData.name,
      category: goodsData.category,
      price: Number(goodsData.price) || 1,
      desc: goodsData.goodsDesc || '',
      img: goodsData.imgUrl 
        ? `${serveUrl}${goodsData.imgUrl}` 
        : ''
    }
  } catch (error) {
    ElMessage.error('数据解析失败: ' + error.message)
    router.back()
  }
}

// 图片上传处理
const handleUploadSuccess = (response) => {
  if (response.code === 0) {
    formData.value.img = `${serveUrl}${response.imgUrl}`;
    ElMessage.success('图片上传成功');
    // 检查图片地址是否正确更新
    if (!formData.value.img) {
      ElMessage.error('图片地址更新失败，请检查上传设置');
    }
  } else {
    ElMessage.error('图片上传失败');
  }
};
onMounted(() => {
  if (!route.query.data) {
    ElMessage.error('缺少商品数据')
    router.replace('/goodsList')
    return
  }
  parseRouteData()
})
</script>

<style lang="scss" scoped>
.title {
    width: 100%;
    height: 50px;
    font-size: 20px;
    color: #333;
    line-height: 50px;
    padding-left: 20px;
    text-align: left;
    border-bottom: 1px solid #dcdfe6;
}
img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-uploader .avatar {
    width: 180px;
    height: 180px;
    display: block;
}

.avatar-uploader.avatar {
    width: 180px;
    height: 180px;
    display: block;
    border: 1px dashed var(--el-border-color);
}

.avatar-uploader.el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader.el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
}

.avatar-uploader {
    width: 180px;
    height: 180px;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    text-align: center;
    line-height: 180px;
    font-size: 28px;
    color: #8c939d;
}

.el-form {
    padding: 20px;
}

.el-button {
    margin-left: 100px;
}
</style>